package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-11-08
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    /**
     * 用户登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //判断参数是否为空
        if(dto==null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查询数据
        LambdaQueryWrapper<AdUser> query=new LambdaQueryWrapper<>();
        query.eq(AdUser::getName,dto.getName());
        AdUser adUser = this.getOne(query);
        //判断用户是否存在,不存在则提示
        if(adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取盐
        String salt = adUser.getSalt();
        //根据用户传来得密码+盐进行加密
        String digest = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        //得到得密码根据数据库进行对比
        if(!digest.equals(adUser.getPassword())){
            //不一致则返回提示
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //一直则生成token返给前端
        Map<String, Object> userInfo=new HashMap<>();
        //传入数据id
        userInfo.put("userId",adUser.getId());
        userInfo.put("userName",adUser.getName());
        String token = AppJwtUtil.getToken(userInfo);
        //定义前端返回格式
        Map<String, Object> resultMap = new HashMap<>();
        //隐藏敏感数据
        adUser.setPassword(null);
        adUser.setPhone(null);
        adUser.setSalt(null);
        resultMap.put("user",adUser);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);
    }
}
